package com.atguigu.yygh.hosp.listener;

import com.atguigu.yygh.common.config.MqConst;
import com.atguigu.yygh.common.config.RabbitService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 杨林
 * @create 2022-11-18 18:07 星期五
 * description: 这是一个rabbitmq的监听器
 */
@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo){

        if (orderMqVo.getAvailableNumber() != null){ //表示监听到支付订单
            //下单成功异步更新号源
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            this.scheduleService.update(schedule);
        }else{  //表示监听到取消订单
            //修改剩余预约数  +1
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            int availableNumber = schedule.getAvailableNumber().intValue();
            schedule.setAvailableNumber(availableNumber + 1);
            scheduleService.update(schedule);
        }

        //向mq发送消息
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (msmVo != null){
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM, msmVo);
        }
    }

}
